package com.lmt.util;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

/**
 * Md5工具类 from:http://hw1287789687.iteye.com/blog/1924190
 * Date 2018/07/17
 *
 * @author MT-Lin
 */
@SuppressWarnings("ALL")
public class Md5Util {

    public static String getFileMD5(File file) {
        if (!file.exists() || !file.isFile()) {
            return null;
        }
        MessageDigest digest;
        FileInputStream in;
        byte[] buffer = new byte[SystemConstant.FILE_READ_BUFFER_SIZE];
        int length;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((length = in.read(buffer, 0, SystemConstant.FILE_READ_BUFFER_SIZE)) != -1) {
                digest.update(buffer, 0, length);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return toHexString(digest.digest());
    }

    /***
     * convert byte array to hex(16) bit string
     *
     * @return hex(16) bit string
     */
    public static String toHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (byte aB : b) {
            sb.append(SystemConstant.HEX_CHAR[(aB & 0xf0) >>> 4]);
            sb.append(SystemConstant.HEX_CHAR[aB & 0x0f]);
        }
        return sb.toString();
    }

    /***
     * Get MD5 of one file！
     *
     * @param filePath 文件路径
     * @return String
     */
    public static String getFileMD5(String filePath) {
        File file = new File(filePath);
        return getFileMD5(file);
    }

    /**
     * MD5 encrypt
     *
     * @param data 数据
     * @return byte[]
     * @throws Exception
     */
    public static byte[] getMD5(byte[] data) throws Exception {
        MessageDigest md5 = MessageDigest.getInstance(SystemConstant.KEY_MD5);
        md5.update(data);
        return md5.digest();
    }

    public static byte[] getMD5(String data) throws Exception {
        return getMD5(data.getBytes(SystemConstant.CHARSET_ISO88591));
    }
}
